package net.lastcoder.ifserver.terminate;

import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;

import java.io.IOException;
import java.io.OutputStream;

/**
 * auth: WenYF
 * date: 2016/11/23
 */
public class TerminateConsoleAppender extends WriterAppender {
    private String target;
    private TerminateSession session;

    public TerminateConsoleAppender(TerminateSession session) {
        this.session = session;
        this.target = "System.out";
        Layout layout = new PatternLayout("%d{yyyy.MM.dd HH:mm:ss} %-5p [%t]: %c - %m%n");
        this.setLayout(layout);
        this.activateOptions();
    }

    public void activateOptions() {
        if(this.target.equals("System.err")) {
            this.setWriter(this.createWriter(new SystemErrStream()));
        } else {
            this.setWriter(this.createWriter(new SystemOutStream()));
        }

        super.activateOptions();
    }

    protected final void closeWriter() {
        super.closeWriter();
    }

    private class SystemOutStream extends OutputStream {
        public SystemOutStream() {
        }

        public void close() {
        }

        public void flush() {
        }

        public void write(byte[] b) throws IOException {
            session.deliverRawData(b);
        }

        public void write(byte[] b, int off, int len) throws IOException {
            session.deliverRawData(b, off, len);
        }

        public void write(int b) throws IOException {
            String str = "" + b;
            session.deliverRawData(str.getBytes());
        }
    }

    private class SystemErrStream extends OutputStream {
        public SystemErrStream() {
        }

        public void close() {
        }

        public void flush() {
        }

        public void write(byte[] b) throws IOException {
            session.deliverRawData(b);
        }

        public void write(byte[] b, int off, int len) throws IOException {
            session.deliverRawData(b, off, len);
        }

        public void write(int b) throws IOException {
            String str = "" + b;
            session.deliverRawData(str.getBytes());
        }
    }
}
